package com.axend.aerosense.room.ui.fragment;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;

import com.axend.aerosense.base.bean.BaseBean;
import com.axend.aerosense.base.fragment.MvvmBaseFragment;
import com.axend.aerosense.base.impl.ILoadDataResult;
import com.axend.aerosense.base.viewmodel.BaseViewModelFactroy;
import com.axend.aerosense.common.util.FragmentUtil;
import com.axend.aerosense.room.BR;
import com.axend.aerosense.room.R;
import com.axend.aerosense.room.databinding.RoomFragmentSceneLearnIngBinding;
import com.axend.aerosense.room.ui.activity.RoomSceneLearnActivity;
import com.axend.aerosense.room.viewmodel.RoomSceneLearnIngViewModel;
import com.blankj.utilcode.util.LogUtils;

import org.jetbrains.annotations.NotNull;


public class RoomSceneLearningFragment extends MvvmBaseFragment<RoomFragmentSceneLearnIngBinding, RoomSceneLearnIngViewModel>
        implements ILoadDataResult<BaseBean> {

    @Override
    public void onViewCreated(@NonNull @NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        showLoading();
        if (getActivity() != null && getActivity().getIntent() != null && getActivity().getIntent().getStringExtra(RoomSceneLearnActivity.RADAR_ID) != null) {
            viewModel.setRadarId(getActivity().getIntent().getStringExtra(RoomSceneLearnActivity.RADAR_ID));
        } else {
            LogUtils.d("Not Radar");
        }
        viewModel.onLoad();
    }

    public void initView() {
        setLoadSir(viewDataBinding.roomConstrainLayout);
        int w = 2800;
        int h = 1890;
        float meterLevel = 6;
        drawScanBg(w, h, meterLevel);
        //到门口位置了
        viewDataBinding.roomButIng.setOnClickListener(v ->
                viewModel.endWebSocket(true)
        );
        viewModel.getIsEndWebSocket().observe(getViewLifecycleOwner(), (aBoolean) -> {
            if (aBoolean) {
                progressbarToMid();
            }
        });
        viewModel.getIsSavePoint().observe(getViewLifecycleOwner(), (aBoolean) -> {
            if (aBoolean) {
                progressbarToFull();
                nextPage();
            }
        });

        viewModel.getCurrentX().observe(getViewLifecycleOwner(), (aFloat) ->
                movePoint(aFloat, viewModel.getCurrentY().getValue() != null ? viewModel.getCurrentY().getValue() : 0)
        );
        viewModel.getCurrentY().observe(getViewLifecycleOwner(), (aFloat) ->
                movePoint(viewModel.getCurrentX().getValue() != null ? viewModel.getCurrentX().getValue() : 0, aFloat)
        );
        viewModel.getRadarWorkDistance().observe(getViewLifecycleOwner(), meterLevel1 -> drawScanBg(w, h, meterLevel1));
        viewModel.getFailWsWork().observe(getViewLifecycleOwner(), aBoolean -> {
            if (aBoolean) {
                nextErrorPage();
            }
        });
        viewModel.getIsReceivePoint().observe(getViewLifecycleOwner(), aBoolean -> {
            if (aBoolean) {
                showContent();
            } else {
                showLoading();
            }
        });
    }

    //画背景弧形
    //meterLevel 设置的扫描米数
    public void drawScanBg(int w, int h, float meterLevel) {
        Bitmap bitmapBg = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvasBg = new Canvas(bitmapBg);
        //画笔
        Paint paintBg = new Paint();
        paintBg.setColor(Color.rgb(250, 250, 250));
        paintBg.setStrokeJoin(Paint.Join.ROUND);
        paintBg.setStrokeCap(Paint.Cap.ROUND);
        paintBg.setAntiAlias(true);//抗锯齿
        paintBg.setStrokeWidth(3);
        //绘制弧线区域
        float bgLeft = (float) (w / 2) - h;
        float bgRight = (float) (w / 2) + h;
        RectF rectBg = new RectF(bgLeft, -h, bgRight, h);
        canvasBg.drawArc(rectBg, //弧线所使用的矩形区域大小
                45,  //开始角度
                90, //扫过的角度
                true, //是否使用中心
                paintBg);
        //绘制弧线区域
        paintBg.setColor(Color.rgb(202, 216, 249));
        float smallRadius = (float) (h / 7) * meterLevel;
        float bgLeft2 = (float) (w / 2) - smallRadius;
        float bgRight2 = (float) (w / 2) + smallRadius;
        RectF rectBg2 = new RectF(bgLeft2, -smallRadius, bgRight2, smallRadius);
        canvasBg.drawArc(rectBg2, //弧线所使用的矩形区域大小
                45,  //开始角度
                90, //扫过的角度
                true, //是否使用中心
                paintBg);

        viewDataBinding.roomImgScanBg.setImageBitmap(bitmapBg);

    }

    //画点
    public void movePoint(float x, float y) {
        //让点不超出在弧形中
        if (Math.abs(x * 2) >= y) {
            if (x >= 0) {
                x = y / 2;
            } else {
                x = -y / 2;
            }
        }
        float z1 = (viewDataBinding.roomLayoutPoint.getHeight() - 50);
        float y1 = y * (z1 / 7);
//        float x1 = Math.abs(x) * (float) ((viewDataBinding.roomLayoutPoint.getWidth()+420) / 7);
        float x1 = Math.abs(x) * (z1 / 7);
        if ((x1 * x1) >= (z1 * z1) - (y1 * y1)) {
            x1 = (float) Math.sqrt((z1 * z1) - (y1 * y1));
        }
        if (x >= 0) {
            x1 = -(x1 + (float) ((viewDataBinding.roomImgScanPoint.getWidth()) / 2)) + (float) (viewDataBinding.roomLayoutPoint.getWidth() / 2);
        } else {
            x1 = (x1 + (float) ((viewDataBinding.roomImgScanPoint.getWidth()) / 2) + (float) (viewDataBinding.roomLayoutPoint.getWidth() / 2));
        }
        viewDataBinding.roomImgScanPoint.setX(x1);
        viewDataBinding.roomImgScanPoint.setY(y1);

        if (viewDataBinding.roomImgScanPoint.getVisibility() == View.GONE) {
            viewDataBinding.roomImgScanPoint.setVisibility(View.VISIBLE);
        }
    }

    public void nextPage() {
        if (viewModel.getClient().isOpen()) {
            viewModel.getClient().closeConnectByUser();
        }
        RoomSceneLearnSuccessFragment fragment = RoomSceneLearnSuccessFragment.getInstance();
        FragmentUtil.add(getActivity() != null ? getActivity() : requireActivity(), ((RoomSceneLearnActivity) getActivity()).getContentId(), fragment, this, true);
    }

    public void nextErrorPage() {
        RoomSceneLearnFailFragment fragment = RoomSceneLearnFailFragment.getInstance();
        FragmentUtil.add(getActivity() != null ? getActivity() : requireActivity(), ((RoomSceneLearnActivity) getActivity()).getContentId(), fragment, this, true);
    }

    //进度条到100%
    public void progressbarToFull() {
        if (viewDataBinding.roomProgressbar.getProgress() != 50) {
            progressbarToMid();
        }
        viewDataBinding.roomProgressbar.setProgress(100);
        String str = String.format(getString(R.string.room_learning_progress), "100");
        viewDataBinding.roomTvProgreessValue.setText(str);
    }


    //进度条到50%
    public void progressbarToMid() {
        viewDataBinding.roomButIng.setVisibility(View.GONE);
        viewDataBinding.roomTvTip2.setVisibility(View.GONE);

        viewDataBinding.roomTvTip1.setText(R.string.room_scene_learn_ing_tips3);
        viewDataBinding.roomProgressbar.setVisibility(View.VISIBLE);
        viewDataBinding.roomTvProgreessValue.setVisibility(View.VISIBLE);

        viewDataBinding.roomProgressbar.setMax(100);
        viewDataBinding.roomProgressbar.setProgress(50);
        String str = String.format(getString(R.string.room_learning_progress), "50");
        viewDataBinding.roomTvProgreessValue.setText(str);
    }

    public static RoomSceneLearningFragment getInstance() {
        return new RoomSceneLearningFragment();
    }

    @Override
    public int getLayoutId() {
        return R.layout.room_fragment_scene_learn_ing;
    }

    @Override
    public int getBindingVariable() {
        return BR.data;
    }

    @Override
    protected RoomSceneLearnIngViewModel getViewModel() {
        BaseViewModelFactroy<BaseBean> factroy = new BaseViewModelFactroy<>(this, this);
        return new ViewModelProvider(this, factroy).get(RoomSceneLearnIngViewModel.class);
    }

    @Override
    protected void onRetryBtnClick() {
        showLoading();
        viewModel.onLoad();
    }


    @Override
    public void loadDataSuccess(BaseBean baseBean) {
//        int w = 2800;
//        int h = 1890;
//        int meterLevel = 5;
//        drawScanBg(w, h, meterLevel);
    }

    @Override
    public void loadDataFail(String decs) {
        showFailure(decs);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        viewModel.endWebSocket(false);
    }
}
